#!/usr/bin/env python
# coding:utf-8

#import serial
import json
import base64
import sys
sys.path.append('./')
from Libs.PipeServer import *

# ======基础配置=======
_ser = None
_ser_timeout = 0.3 #300ms超时
_ser_resend=6#通讯重发次数
# =================

#串口通讯api：返回通讯原始数据
def comm_serial(data, recv_len):
    timeout_count = 0
    recv=b''
    '''
    while timeout_count< _ser_resend:
        _ser.flushInput()
        try:
            _ser.write(data)
        except:
            pass
        #等待数据写出，貌似没有必要
        #_ser.flush()
        
        recv = _ser.read(recv_len)
        if len(recv)==recv_len:
            #print("recv_IO:",recv)
            return recv
        timeout_count = timeout_count + 1
        #在发生错误后睡眠50ms接收异常返回数据
        time.sleep(0.05)
        #接收错误后再清空flush write区的数据
        _ser.flush()

    '''
    recv=b'Im Back'
    #超过重发次数返回，无数据返回None,否则返回数据
    if recv==b'':
        return None
    else:
        return recv

def onDataRecv(data):
    req = data 
    #判定json格式
    try:
        args = json.loads(req)
    except ValueError as e:
        obj = {"errcode":2001, "rtval":None}
        return json.dumps(obj)
        return
        
    #判定json参数
    try:
        data = base64.b64decode(bytes(args['data'], encoding='utf-8'));
        recv_len = args['recv_len'];
    except Exception as e:
        obj = {"errcode":2002, "rtval":None}
        return json.dumps(obj)

    #判定recv_len是数字
    if str(recv_len).isdigit():
        #通讯原始数据发送回收处理
        rep = comm_serial(data, recv_len)
        if rep == None:
            obj = {"errcode":2004, "rtval":None}
        else:
            if len(rep)!=recv_len:
                obj = {"errcode":2005, "rtval":str(base64.b64encode(rep), encoding='utf-8')}
            else:
                obj = {"errcode":0, "rtval":str(base64.b64encode(rep), encoding='utf-8')}
        #if int(pipeNumber)==1 and pipeName=="Pipe485S0":
        #    if rep!=None:
        #        new=[]
        #        for i in str(rep):
        #            new.append(ord(i))
        #        print(new)
        #    else:
        #        print( None)
        return json.dumps(obj)
    else:
        obj = {"errcode":2003, "rtval":None}
        return json.dumps(obj)

if __name__ == "__main__":

    if len(sys.argv)<8:
        print("Not enough parameters  e.g. python3 serial2pipe_server.py /dev/ttyS0 115200 8 N 1 Pipe485S0 5")
        sys.exit()
        
    port =  sys.argv[1]
    baudrate = sys.argv[2]
    bytesize = sys.argv[3]
    parity     = sys.argv[4]
    stopbits  = sys.argv[5]
    pipeName = sys.argv[6]
    pipeNumber = sys.argv[7]
    
    
    if str(baudrate).isdigit() and str(bytesize).isdigit() and str(stopbits).isdigit():
        #_ser = serial.Serial(port=port, baudrate=int(baudrate), bytesize=int(bytesize), parity=parity, stopbits=int(stopbits), write_timeout=_ser_timeout, timeout=_ser_timeout)
        print("create serial port")
    else:
        print("baudrate and bytesize and stopbits must be number")
        sys.exit()
        
    p = None
    if str(pipeNumber).isdigit():
        p = PipeServer(pipeName, int(pipeNumber), onDataRecv )
    else:
       print("pipeNumber must be number")
       sys.exit()


    print("485ToPipeServer [", port ,"] has been initialized ...")
    
    while True:
        time.sleep(10)
        
